//
//  EDSearchResultViewController.m
//  EDF
//
//  Created by p on 2019/7/24.
//  Copyright © 2019年 p. All rights reserved.
//

#import "EDSearchResultViewController.h"
#import "PTCollectionViewCell.h"
#import "PTModel.h"
#import "LLWebViewController.h"
@interface EDSearchResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
{
    UIView *_bgView;
    UITextField *_textField;
}
@property (nonatomic,strong)UICollectionView * collectionV;
@property(nonatomic,strong)NSMutableArray * dataSource;
@property (nonatomic,strong) NoNetworkView * workView;
@end

@implementation EDSearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
    self.navigationItem.title = @"";
    [self setupSearchBar];
    [self getResult:_name];
    [self.view addSubview:self.collectionV];
}
- (void)getResult:(NSString *)name
{
    [self showLoadingAnimation];
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameQuery"];
    NSDictionary * parame = @{@"displayname":name};
    [[SmileHttpTool sharedInstance] GET :game parameters:parame origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
        [self stopLoadingAnimation];
        NSDictionary * dic = [self objectFromJSONString:responseObject];
        if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
        {
            NSDictionary * dic = [self objectFromJSONString:responseObject];
            self.dataSource  = [PTModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
            [self placeholderViewWithFrame:self.collectionV.frame NoNetwork:NO];
            [self.collectionV reloadData];
           
        }else
        {
            [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
        }
        
        
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        
    }];
}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.dataSource.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        
        [_collectionV addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
}
-(void)setupSearchBar{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 30)];
    //设置圆角效果
    bgView.layer.cornerRadius = 2;
    bgView.layer.masksToBounds = YES;
    
    bgView.backgroundColor = [UIColor whiteColor];
    //输入框
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, CGRectGetWidth(bgView.frame) - 20, CGRectGetHeight(bgView.frame))];
    _textField.font = AutoFont(14);
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    imageView.image = [UIImage imageNamed:@"search"];
    _textField.leftView = imageView;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    _textField.textColor = RGBA(68, 68, 68, 1);
    //清除按钮
    _textField.clearButtonMode =UITextFieldViewModeWhileEditing;
    
    _textField.delegate = self;
    //键盘属性
    _textField.returnKeyType = UIReturnKeySearch;
    
    //为textField设置属性占位符
    _textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入游戏名称" attributes:@{NSForegroundColorAttributeName:RGBA(161, 161, 161, 1)}];
    _textField.textAlignment = NSTextAlignmentCenter;
    
    
    [bgView addSubview:_textField];
    
    self.navigationItem.titleView = bgView;
    
}
//输入框开始编辑
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

}


-(void)clickCancel{
    [_textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (!kStringIsEmpty(textField.text)) {
         [self getResult:textField.text];
         [_searchVM saveHistory:textField.text];
    }
   
    [textField resignFirstResponder];
    return YES;
}
#pragma  mark -----懒加载
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (UICollectionView *)collectionV
{
    if (!_collectionV) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0,
                                                                         kStatusBarAndNavigationBarHeight,
                                                                         UIScreenWidth,
                                                                         UIScreenHeight -kStatusBarAndNavigationBarHeight) collectionViewLayout:layout];
        _collectionV.backgroundColor = RGBA(240, 240, 240, 1);
        _collectionV.delegate =self;
        _collectionV.dataSource= self;
        [_collectionV registerNib:[UINib nibWithNibName:@"PTCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PTCollectionViewCell"];
        _collectionV.showsVerticalScrollIndicator = NO;
        _collectionV.showsHorizontalScrollIndicator = NO;
    }
    return _collectionV;
    
}
#pragma mark---UICollectionViewDelgate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PTCollectionViewCell *item = [self.collectionV dequeueReusableCellWithReuseIdentifier:@"PTCollectionViewCell" forIndexPath:indexPath];
    PTModel * model = _dataSource[indexPath.row];
    item.model = model;
    NSString * str = kFormat(@"%@ %@", [WJUnit getGameIcon:model.plat_id],model.displayname);
    [item.collBtn setTitle:str forState:0];
    item.collBtn.selected = model.isusergame;
    [item.collBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -item.collBtn.imageView.width , 0, item.collBtn.imageView.width)];
    [item.collBtn setImageEdgeInsets:UIEdgeInsetsMake(0, item.collBtn.titleLabel.width , 0, - item.collBtn.titleLabel.width)];
    if ([model.istrial isEqualToString:@"是"]) {
        item.playBat.hidden = NO;
        
        item.top.constant =1;
    }else
    {
        item.playBat.hidden = YES;
        item.top.constant -=10;
    }
    WeakSelf
    [item.collBtn add_BtnClickHandler:^(NSInteger tag) {
        item.collBtn.userInteractionEnabled = NO;
        NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"addUserLikeGame"];
        [[SmileHttpTool sharedInstance] GET :game parameters:@{@"gameid":model.gameid} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
            
            NSDictionary * dic = [WJUnit dictionaryWithJsonString:responseObject];
            item.collBtn.userInteractionEnabled = YES;
            if ([[dic jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                
                if (model.isusergame) {
                    
                    
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:@"取消收藏成功" andlightStr:@""];
                    [toast showLXAlertView];
                    
                    model.isusergame = NO;
                    
                }else
                {
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:@"收藏成功" andlightStr:@""];
                    [toast showLXAlertView];
                    model.isusergame = YES;
                }
            }else
            {
                [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
            }
            
            [weakSelf.collectionV reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:0]]];
            
            
        } failure:^(id responseObject, NSError *error) {
            item.collBtn.userInteractionEnabled = YES;
            [WJUnit showMessage:@"请求错误"];
            
        }];
    }];
    [item.playBat add_BtnClickHandler:^(NSInteger tag) {
        
        [self getGameURLWithModel:model editInfo:@"offline"];
    }];
    item.getGameUrlBlock = ^(PTModel * _Nonnull modle) { //图片需要真实玩 需要登录的
        
        [self getGameURLWithModel:model editInfo:@"online"];
    };
    return item;
    
}
- (void)getGameURLWithModel:(PTModel *)model editInfo:(NSString *)editInfo
{
    if ([editInfo isEqualToString:@"REAL"]) {
        if (![DJLoginHelper sharedInstance].is_Login) {
            
            [[DJLoginHelper sharedInstance]dj_showLoginVC:self];
            return;
        }
    }
    [self showLoadingAnimation];
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameUrl"];
    NSDictionary * parame = @{@"mode":editInfo,@"gameid":model.gameid,@"plat_id":model.plat_id,@"gamecode":model.gamecode};
    [[SmileHttpTool sharedInstance] GET :game parameters:parame origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
        [self stopLoadingAnimation];
        NSDictionary * dic = [self objectFromJSONString:responseObject];
        if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
        {
            LLWebViewController * webview = [[LLWebViewController alloc] init];
            webview.urlStr = dic[@"data"];
             webview.isType = 3;
            webview.isShowGame = YES;
            [self.navigationController pushViewController:webview animated:YES];
        }else
        {
            [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
        }

    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        
    }];
}
//定义每个Section的四边间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5);//分别为上、左、下、右
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake(UIScreenWidth/3 -1 ,140);
    return size;
}
//两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return RealValue_W(0.5);
}
//这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return RealValue_W(1);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    Mine *mine = _dataSource[indexPath.row];
    //    ServerDetailsViewController * ServerDetailsVC = [[ServerDetailsViewController alloc] init];
    //    ServerDetailsVC.hidesBottomBarWhenPushed = YES;
    //    ServerDetailsVC.title = @"服务器详情";
    //    ServerDetailsVC.server_id = mine.id;
    //    [self.navigationController pushViewController:ServerDetailsVC animated:YES];;
}
@end
